package cn.ming.leo.resource;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import cn.ming.leo.bean.User;
import cn.ming.leo.service.UserService;
import cn.ming.leo.utils.Constant.MsgCode;
import cn.ming.leo.utils.Message;
import cn.ming.leo.utils.TimeFormat;
import cn.ming.leo.bean.SysCode;

@RestController
@RequestMapping("/user")
public class UserResource {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	public Message<String> regist(String mobile, String code, String openId) {
		return userService.regist(mobile, code, openId);
	}

	@RequestMapping(value = "/getCode", method = RequestMethod.POST)
	@ResponseBody
	public Message<String> regist1(String mobile) throws ClientException {
		String code = TimeFormat.getCode();
		int count = User.find.where().eq("mobile", mobile).findRowCount();
		if (count > 0) {
			return new Message<String>(MsgCode.FAIL.value, "手机号已注册", "手机号已注册");
		}
		boolean reulst = getCode(mobile, code);
		if (reulst) {
			SysCode s = SysCode.find.where().eq("mobile", mobile).findUnique();
			if (s != null) {
				s.delete();
			}

			SysCode sysCode = new SysCode();
			sysCode.setCreateTime(TimeFormat.nowTime());
			sysCode.setCode(code);
			sysCode.setMobile(mobile);
			sysCode.insert();
		}else {
			return new Message<String>("发送失败");

		}

		return new Message<String>("发送成功");
	}

	private boolean getCode(String mobile, String code) throws ClientException {
		// 设置超时时间-可自行调整
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		// 初始化ascClient需要的几个参数
		final String product = "Dysmsapi";// 短信API产品名称（短信产品名固定，无需修改）
		final String domain = "dysmsapi.aliyuncs.com";// 短信API产品域名（接口地址固定，无需修改）
		// 替换成你的AK
		final String accessKeyId = "yqptmrzVstktHVVj";// 你的accessKeyId,参考本文档步骤2
		final String accessKeySecret = "WRG0IIIXJrfy66em4FlKMERxzFLzQ3";// 你的accessKeySecret，参考本文档步骤2
		// 初始化ascClient,暂时不支持多region（请勿修改）
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
		DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		IAcsClient acsClient = new DefaultAcsClient(profile);
		// 组装请求对象
		SendSmsRequest request = new SendSmsRequest();
		// 使用post提交
		request.setMethod(MethodType.POST);
		// 必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为国际区号+号码，如“85200000000”
		request.setPhoneNumbers(mobile);
		// 必填:短信签名-可在短信控制台中找到
		request.setSignName("爱拓智能柜");
		// 必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
		request.setTemplateCode("SMS_153795065");
		Map<String, Object> map = new HashMap<>();
		map.put("code", code);
		request.setTemplateParam(JSON.toJSONString(map));
		SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
		if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
			return true;
		}

		return false;
	}

}
